<?php
namespace Home\Controller;
use Think\Controller;
class OrderController extends CommonController {
	
	/**
     * [token token验证]
     * @return [type] [json]
     */
	public function __construct(){
		//$this->token();
	}

    /**
     * 待付款
     */
	public function payment($uid,$pno,$pgz){
        $pindex = $pno ;     //当前页码
        $psize  = $pgz ;   //显示条数
        if(!$pindex)  $pindex = 1;
        $pfirst = ($pindex - 1) * $psize;
        $order = M('order');

        $where['order_state'] = 10;
        $where['buyer_id'] = $uid;
        $where['delete_state'] = 0;
        $data = $order->field("order_id,order_sn,store_id,pay_sn,order_amount,buyer_id,order_amount,order_state,evaluation_state")->where($where)->limit($pfirst .','.$psize)->order(array('order_id'=>'desc'))->select();
        $goods = M('order_goods');
        foreach($data as $k=>$v){
            $order_id = $v['order_id'];
            $goods_data =$goods->where("order_id = $order_id")->select();
            $data[$k]['goods_list'] = $goods_data;
        }
        if(!$data){
            returnArr('ok');
        }
        returnApiSuccess('ok',$data);
    }

    /**
     * 待评价
     */
    public function evaluation($uid,$pno,$pgz){
        $pindex = $pno ;     //当前页码
        $psize  = $pgz ;   //显示条数
        if(!$pindex)  $pindex = 1;
        $pfirst = ($pindex - 1) * $psize;
        $order = M('order');
        $refund = M('refund_return');
        $where['evaluation_state '] = 0;
        $where['order_state'] = 40;
        $where['buyer_id'] = $uid;
        $where['delete_state'] = 0;
        $data = $order->field("order_id,order_sn,store_id,pay_sn,order_amount,buyer_id,order_amount,order_state,evaluation_state")->where($where)->limit($pfirst .','.$psize)->order(array('order_id'=>'desc'))->select();

        $goods = M('order_goods');
        foreach($data as $k=>$v){
            $order_id = $v['order_id'];
            $goods_data = $goods->where("order_id = $order_id")->select();

            $data[$k]['goods_list'] = $goods_data;
            foreach($goods_data as $k2=>$v2){
                $orderid = $v2['order_id'];
                $refund_data = $refund->field('refund_type,order_id')->where("order_id = $order_id and refund_type = 1 and order_id = $orderid")->find();
                if($refund_data){
                     $data[$k]['goods_list'][$k2]['refund_type'] = 1;
                   // $data[$k]['goods_list'][$k2]['refund_type'] = 1;
                }else{
                     $data[$k]['goods_list'][$k2]['refund_type'] = 0;
                   // $data[$k]['goods_list']['refund_type'] = 0;
                }
                //print_r( $v2);die;

            }



        }
       
        if(!$data){
            returnArr('ok');
        }
        returnApiSuccess('ok',$data);
    }

    /**
     * 待收货
     */
    public function receipt($uid,$pno,$pgz){
        $pindex = $pno ;     //当前页码
        $psize  = $pgz ;   //显示条数
        if(!$pindex)  $pindex = 1;
        $pfirst = ($pindex - 1) * $psize;
        $order = M('order');
        $where['order_state'] = 30;
        $where['buyer_id'] = $uid;
        $where['delete_state'] = 0;
       
        $data = $order->field("order_id,order_sn,store_id,pay_sn,order_amount,buyer_id,order_amount,order_state,evaluation_state")->where($where)->limit($pfirst .','.$psize)->order(array('order_id'=>'desc'))->select();
        //echo $order->getLastSql();die;
        $goods = M('order_goods');
        foreach($data as $k=>$v){
            $order_id = $v['order_id'];
            $goods_data =$goods->where("order_id = $order_id")->select();
            $data[$k]['goods_list'] = $goods_data;
        }
        if(!$data){
            returnArr('ok');
        }
        returnApiSuccess('ok',$data);
    }

    public function whole($uid,$pno,$pgz){
        $pindex = $pno ;     //当前页码
        $psize  = $pgz ;   //显示条数
        if(!$pindex)  $pindex = 1;
        $pfirst = ($pindex - 1) * $psize;
        $order = M('order');
        $refund = M('refund_return');
        $where['buyer_id'] = $uid;
        $where['delete_state'] = 0;

        $data = $order->field("order_id,order_sn,store_id,pay_sn,order_amount,buyer_id,order_amount,order_state,evaluation_state")->where($where)->limit($pfirst .','.$psize)->order(array('order_id'=>'desc'))->select();
        $goods = M('order_goods');
        foreach($data as $k=>$v){
            $order_id = $v['order_id'];
            $goods_data =$goods->where("order_id = $order_id")->select();
            $data[$k]['goods_list'] = $goods_data;


        }
        if(!$data){
            returnArr('ok');
        }
        returnApiSuccess('ok',$data);
    }

    public function deliver($uid,$pno,$pgz){
        $pindex = $pno ;     //当前页码
        $psize  = $pgz ;   //显示条数
        if(!$pindex)  $pindex = 1;
        $pfirst = ($pindex - 1) * $psize;
        $order = M('order');

        $where['order_state'] = 20;
        $where['buyer_id'] = $uid;
        $where['delete_state'] = 0;
        $data = $order->field("order_id,order_sn,store_id,pay_sn,order_amount,buyer_id,order_amount,order_state,evaluation_state")->where($where)->limit($pfirst .','.$psize)->order(array('order_id'=>'desc'))->select();
        $goods = M('order_goods');
        foreach($data as $k=>$v){
            $order_id = $v['order_id'];
            $goods_data =$goods->where("order_id = $order_id")->select();
            $data[$k]['goods_list'] = $goods_data;
        }
        if(!$data){
            returnArr('ok');
        }
        returnApiSuccess('ok',$data);
    }

	/**
     * [orderlist 订单列表]
     * @return [type] [json]
     */
	public function orderlist(){
        $uid = I('post.uid',0,'intval');
        if(!$uid)   returnApiError(1,'用户id参数错误');
        //$this->usertoken($uid);
		$state = I('post.order_state');
        if(!$uid)   returnApiError(1,'order_id参数错误');
        $pno = I('post.pno',1,'intval') ;     //当前页码
        $pgz  = I('post.pgz',10,'intval') ;   //显示条数
        if($state == 1){
            $this->payment($uid,$pno,$pgz);
        }
        if($state == 2){
            $this->receipt($uid,$pno,$pgz);
        }
        if($state == 3){
            $this->evaluation($uid,$pno,$pgz);
        }
        if($state == 4){
            $this->whole($uid,$pno,$pgz);
        }

        if($state == 5){
            $this->deliver($uid,$pno,$pgz);
        }


    }

    /**
     * 订单详情
     */
    public function orderdetail(){
        $orderid = I('post.orderid');
        if(!$orderid)   returnApiError(1,'用户orderid参数错误');
        $order = M('order');
        $order_common = M('order_common');
        $data = $order->find($orderid);
        if($data['payment_code'] == 'alipay'){
            $data['payment_code'] = '支付宝支付';
        }
        if($data['payment_code'] == 'wxpay'){
            $data['payment_code'] = '微信支付';
        }
        if($data['payment_code'] == 'offline'){
            $data['payment_code'] = '线下支付';
        }
        if($data['payment_code'] == 'online'){
            $data['payment_code'] = '线上支付';
        }

        $orderid = $data['order_id'];
        $common_data = $order_common->find($orderid);
        $data['reciver_name'] = $common_data['reciver_name'];
        $data['reciver_info'] = unserialize($common_data['reciver_info']);
        if($data){
            returnApiSuccess('ok',$data);
        }

        returnArr('空数据');

    }

    /**
     * 删除订单
     */
    public function delorder(){
        $orderid = I('post.orderid');
        if(!$orderid)   returnApiError(1,'用户orderid参数错误');
        $order = M('order');
        $data = $order->find($orderid);
        if(!$data)  returnApiError(1,'订单不存在');
        if($data['order_state'] == 30  || $data['order_state'] == 20  ){
            returnApiError(1,'当前状态不能删除');
        }

        $save['delete_state'] = 2;
        $order->where("order_id = $orderid")->save($save);


        returnApiSuccess('ok');
    }

    /**
     * 订单统计
     */
    public function countorder(){
        $uid = I('post.uid');
        if(!$uid)   returnApiError(1,'用户id参数错误');

        //$this->usertoken($uid);
        $model = M('order');
        $member = M('member');
        $pay_where['buyer_id'] = $uid;
        $pay_where['order_state'] = 10;
        $pay_where['delete_state'] = 0;

        $receipt_map = " buyer_id = $uid and (order_state = 30 or order_state = 20) and delete_state = 0";
        $deliver_map = "buyer_id = $uid and order_state = 20  and delete_state = 0";

        $evaluation_where['buyer_id']  = $uid;
        $evaluation_where['evaluation_state']  = '0';
        $evaluation_where['order_state']  = '40';
        $evaluation_where['delete_state'] = '0';

        $paymentCount = $model->where($pay_where)->count();     //待付款
       // echo $model->getLastSql();
        $receiptCount = $model->where($receipt_map)->count(); //待收货
        $deliver_Count = $model->where($deliver_map)->count(); //待发货
        // echo $model->getLastSql();die;
        $evaluationCount = $model->where($evaluation_where)->count(); //待评价

        $member_data = $member->field('member_points,available_predeposit')->where("member_id = $uid")->find();

        $voucher = M('voucher_quota');
        $voucherCount = $voucher->where("quota_memberid = $uid")->count();

        //申请售后统计
        $refund = M('refund_return');
        $refundnCount = $refund->where("buyer_id = $uid")->count(); //待评价
        $data = array(
            'paymentCount' => $paymentCount,
            'receiptCount' => $receiptCount,
            'deliver_Count' =>$deliver_Count,
            'evaluationCount' => $evaluationCount,
            'available_predeposit' =>$member_data['available_predeposit'],
            'member_points' =>$member_data['member_points'],
            'voucher' => $voucherCount,
            'refundnCount' => $refundnCount,
        );

       // var_dump($data);die;
        returnApiSuccess('ok',$data);
    }

    /**
     * 订单搜索
     */
    public function ordersearch(){
        $keyword = I('post.keyword');
        $uid = I('post.uid',0,'intval');
        //$this->usertoken($uid);
        $pindex = I('post.pno',1,'intval') ;     //当前页码
        $psize  = I('post.pgz',10,'intval') ;   //显示条数
        if(!$pindex)  $pindex = 1;
        $pfirst = ($pindex - 1) * $psize;
        if(!$uid)   returnApiError(1,'请传入用户uid');
        if(!$keyword) returnApiError(1,'请输入关键词');

        $model = M('order');
        $goods = M('order_goods');
        /* $goods = C('DB_PREFIX').'order_goods';
         $order = C('DB_PREFIX').'order';
         $con = " and $goods.goods_name like '%$keyword%' ";
         $data = $model->field("$goods.*,$order.order_id,$order.order_sn,$order.store_id,$order.pay_sn,$order.buyer_id,$order.order_amount")->join("$order ON $goods.order_id = $order.order_id  and $order.buyer_id = $uid.$con")->limit($pfirst .','.$psize)->select();
        */
        $data = $model->where("buyer_id=$uid")->limit($pfirst .','.$psize)->select();
        foreach($data as $k=>$v){
            $orderid = $v['order_id'];

            $goods_data = $goods->where("order_id = $orderid and goods_name like '%$keyword%'")->select();
            if(!$goods_data){
                unset($data[$k]);continue;
            }
            $data[$k]['goodslist'] = $goods_data;
        }
        $data = array_values($data);
        if(!$data){
            returnArr('数据为空');
        }else{
            returnApiSuccess('ok',$data);
        }
    }
    /**
     * 确认收货
     */
    public function confirmreceipt(){
        $order_sn = I('post.order_sn');
        if(!$order_sn) returnApiError(1,'缺少order_sn参数');
        $save['order_state'] = 40;
        $model = M('order');
        $where['order_sn'] = $order_sn;
        if($model->where($where)->save($save)){
            returnApiSuccess('修改成功');
        }else{
            returnApiError(1,'修改失败');
        }
    }


    /**
     * [ordergoods 订单商品]
     * @return [type] [json]
     */
	public function ordergoods(){
		$orderid = I('post.orderid',0,'intval');
		if(!$orderid)   returnApiError(1,'订单id参数错误');

		$where['order_id'] = $orderid;
        $model = M('order_goods');
        $goods = C('DB_PREFIX').'order_goods';
        $order = C('DB_PREFIX').'order';

        $data = $model->field("$goods.*,$order.order_id,$order.order_sn,$order.store_id,$order.pay_sn,$order.buyer_id,$order.order_amount")->join("$order ON $goods.order_id = $order.order_id  and $order.order_id = $orderid")->select();
        foreach($data as $k=>$v){
            $data[$k]['goods_image'] = 'data/upload/shop/store/goods/'.$v['store_id'].'/'.$v['goods_image'];
        }

        if($data){
            returnApiSuccess('ok',$data);
        }
        returnArr('数据为空');

	}


    /**
     * 清空订单
     */
    public function orderdel()
    {
        $uid = I('post.uid');
        //$this->usertoken($uid);
        $model = M('order');
        $goods = M('order_goods');
        $model->where("buyer_id=$uid")->delete();
        $goods->where("buyer_id=$uid")->delete();
    }




    /**
     * 满即送活动
     */
    public function mansong(){
        echo "<pre>";
        $uid = 8;
        $ManSong = M('p_mansong');
        $Cart = M("Cart");
        $arr = array();

        $store = $this->getstore($uid);
        foreach($store as $k=>$v){
            $store_id = $v['store_id'];
            $where['buyer_id'] = $uid;
            $where['store_id'] = $store_id;
            $cart_data = $Cart->where($where)->select();
            foreach($cart_data as $v2){
                $goods_price[$k] += $v2['goods_price'];
            }
            $arr[$k]['store_id']= $store_id;
            $arr[$k]['price']= $goods_price[$k];
        }

        foreach($arr as $v3){
            $mansong_result = $ManSong->select();
        }

        echo "<hr />";
        //var_dump($store);
        var_dump($arr);
    }

    /**
     * 购买价格
     */
    public function orderprice($uid,$city_id){

        $uid =  $uid ? $uid : I('post.uid');
        if(!$uid){
            returnApiError(1,'缺少uid参数');
        }
        $city_id = $city_id ? $city_id : I('post.city_id');
        if(!$city_id){
            returnApiError(1,'缺少city_id参数');
        }

        //商品价格
        $goods_price = $this->createOrderStep1($uid);

        //运费
        $transport = $this->transport($uid,$city_id);

        $data['price'] = $goods_price['price'];
        $data['promotion_price'] = $goods_price['promotion_price'];
        $data['transport'] = $transport;

        returnApiSuccess('ok',$data);
    }

    public function payprice($uid,$city_id){


        //商品价格
        $goods_price = $this->createOrderStep1($uid);

        //运费
        $transport = $this->transport($uid,$city_id);

        $data['price'] = $goods_price['price'];
        $data['promotion_price'] = $goods_price['promotion_price'];
        $data['transport'] = $transport;

        return $data;
    }

    /**
     * 商品价格
     */
    public function createOrderStep1($uid){
        $Cart = M("Cart");
        $where['buyer_id'] = $uid;
        $data = $Cart->where($where)->select();
        if(!$data){
            returnApiError(1,'购物车数据失效');
        }

        //商品实例化查询

        $Archives = M('Goods');
        foreach($data as $k=>$v){
            $goodsid = $v['goods_id'];
            $goods_where['goods_id'] = $goodsid;
            $goods_result = $Archives->where($goods_where)->find();

            if(!$goods_result)   returnApiError(1,'商品不存在');
            if($goods_result['goods_state'] == 0) returnApiError(1,$goods_result['goods_name'].'已下架');
            if($goods_result['goods_storage'] == $goods_result['goods_storage_alarm'])  returnApiError(1,'库存不足');
            $promotion_price += $goods_result['goods_promotion_price']*$v['goods_num'];
            $price += $goods_result['goods_price']*$v['goods_num'];
        }

        $price_arr['price'] = $price;
        $price_arr['promotion_price'] = $promotion_price;

        return $price_arr;
    }

    /*
     * 运费
     */
    public function transport($uid,$city_id){

        $mobel_transport_extend = M('TransportExtend');
        $mobel_transport = M('Transport');

        //购物车店铺列表
        $store_list = $this->getstore($uid);

        //售卖区域
        $freight = 0;
        $transport_arr = array();
        foreach($store_list  as $v){
            $map['store_id'] = $v['store_id'];
            $transport_arr[] = $mobel_transport->where($map)->find();
        }

        if($transport_arr){
            foreach($transport_arr as $v){
                $transport_result[] = $mobel_transport_extend->find($v['id']);
            }
        }

        foreach( $transport_result as $v){
            $area_id = trim($v['area_id'],',');
            $area_arr = explode(',',$area_id);
            foreach($area_arr as $a){
                if($city_id == $a){
                    $freight += $v['sprice'];
                }
            }

        }

        return $freight;
    }

    /**
     * 购物车店铺列表
     *
     */
    public function getstore($uid){
        $Cart = M("Cart");
        $where['buyer_id'] = $uid;
        $data = $Cart->where($where)->group("store_id")->select();
        return $data;
    }

    /**
     * 购物车列表
     *
     */
    public function getcart($uid){
        $Cart = M("Cart");
        $where['buyer_id'] = $uid;
        $data = $Cart->where($where)->select();
        return $data;
    }


    /**
     * 下单
     */
    public function  createorder(){
        $uid = I('post.uid');
        //$this->usertoken($uid);
        $city_id  = I('post.city_id');
        $reciver_name = I('post.reciver_name');

        $reciver_info = $_POST['reciver_info'];


        if($_POST['address_id']){
            $address = M('address');
            $add_data = $address->find($_POST['address_id']);
            $phone = $add_data['mob_phone'];
            $json_arr = array(
                'phone' => $phone,
                'mob_phone' =>$phone,
                'tel_phone' => $phone,
                'address' => $add_data['area_info'].$add_data['address'],
                'area' => $add_data['area_info'],
                'street' => $add_data['address'],
            );
            $reciver_info = serialize($json_arr);
        }else{
            if(!$reciver_info){
                returnApiError(1,'缺少reciver_info参数');
            }
            $reciver_info = serialize(json_decode($_POST['reciver_info'],true));
        }
        if(!$uid){
            returnApiError(1,'缺少uid参数');
        }
        if(!$city_id){
            returnApiError(1,'缺少city_id参数');
        }
        if(!$reciver_name){
            returnApiError(1,'缺少reciver_name参数');
        }


        $area = M('area');
        $pro = $area->where("area_id=$city_id")->find();
        $province_id = $pro['area_parent_id'];

        $Model = D('order');
        $order_pay = M('order_pay');
        $order_goods = M('order_goods');
        $order_common = M('order_common');
        $ordersn = $Model->orderSn($uid);
    
        $paysn = $Model->makePaysn($uid);
        $price = $this->payprice($uid,$city_id);
        $mycart = $this->getcart($uid);
        if(!$mycart)  returnApiError(1,'购物车为空');

        $store_id = $mycart[0]['store_id'];
        $store = M('store')->where("store_id=$store_id")->find();
        $store_name = $store['store_name'];
        $member = M('member')->where("member_id = $uid")->find();
        $order_data = array(
            'order_sn' => $ordersn,
            'pay_sn' => $paysn,
            'store_id' =>  $store_id,
            'store_name' =>  $store_name,
            'buyer_id' => $uid,
            'buyer_name' => $member['member_name'],
            'buyer_email' => $member['member_email'],
            'add_time' => time(),
            'payment_code' => 'online',
            'goods_amount' => $price['promotion_price'],
            'order_amount' => $price['promotion_price']+$price['transport'],
            'order_state' => 10,
            'shipping_fee' => $price['transport'],
        );
        $order_pay_data = array(
            'pay_sn' => $paysn,
            'buyer_id' => $uid,
            'api_pay_state' => 0,
        );

        $callback = true;
        if(!$order_id = $Model->add($order_data)){
            $callback = false;
        }

        if(!$order_pay->add($order_pay_data)){
            $callback = false;
        }

        $order_common_data = array(
            'order_id' => $order_id,
            'store_id' => $store_id,
            'reciver_name' => $reciver_name,
            'reciver_info' => $reciver_info,
            'reciver_city_id'=> $city_id,
            'reciver_province_id'=> $province_id,
            'evalseller_time'=> 0,
        );
        if(!$order_common->add($order_common_data)){
            $callback = false;
        }

        foreach($mycart as $v){
            $order_goods_data = array(
                'order_id' => $order_id,
                'goods_id' => $v['goods_id'],
                'goods_name' => $v['goods_name'],
                'goods_price' => $v['goods_price'],
                'goods_num' => $v['goods_num'],
                'goods_image'=> $v['goods_image'],
                'goods_pay_price' => $v['goods_price'],
                'store_id' => $store_id,
                'buyer_id' => $uid,
                'goods_type' => 1,
                'gc_id' => 0,
            );
            if(!$order_goods->add($order_goods_data)){
                $callback = false;
            }
        }



        if($callback){
            $Model->commit();
            $order_common->commit();
            $order_goods->commit();
            $order_pay->commit();
            $data = array(
                'order_sn' => $paysn,
            );
            returnApiSuccess('ok',$data);
        }else{
            $Model->rollback();
            $order_common->rollback();
            $order_goods->rollback();
            $order_pay->rollback();

            returnApiError(1,'下单失败');
        }


    }

    /**
     * 物流查询
     */
    public function logistics(){
       /* $orderid  = I('orderid');

        $order = M('order');
        $order_common = M('order_common');
        $express = M('express');

        $result = $order->find($orderid);
        //if(!$result) returnApiError(1,'订单不存在');
        $typeNu = $result['shipping_code'];

        $common = $order_common->find($orderid);
        //if(!$common) returnApiError(1,'未设置快递公司');

        $shipping_express_id = $common['shipping_express_id'];
        $express_data = $express->where("id = $shipping_express_id")->find();
        $typeCom = $express_data['e_code'];

        //$typeCom = 'yuantong';//快递公司
        //$typeNu = '881764045260833586';  //快递单号

       // $AppKey='16135ea51cb60246eff620f130a005bd';//请将XXXXXX替换成您在http://kuaidi100.com/app/reg.html申请到的KEY
        //$url ='http://api.kuaidi100.com/api?id='.$AppKey.'&com='.$typeCom.'&nu='.$typeNu.'&show=0&muti=1&order=asc';
*/
        $url = "http://api.ickd.cn/?id=102616&secret=16135ea51cb60246eff620f130a005bd&com=yuantong&nu=881764045260833586&type=json&encode=utf8&ord=desc";
        //$url = "http://api.ickd.cn/?id=102616&secret=16135ea51cb60246eff620f130a005bd&com=$typeCom&nu=$typeNu&type=json&encode=utf8&ord=asc";
        $curl = curl_init();
        curl_setopt ($curl, CURLOPT_URL, $url);
        curl_setopt ($curl, CURLOPT_HEADER,0);
        curl_setopt ($curl, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt ($curl, CURLOPT_USERAGENT,$_SERVER['HTTP_USER_AGENT']);
        curl_setopt ($curl, CURLOPT_TIMEOUT,5);
        $get_content = curl_exec($curl);
        curl_close ($curl);
       /* $get_content = '{"message":"ok","status":"1","state":"3","data":
            [{"time":"2012-07-07 13:35:14","context":"客户已签收"},
             {"time":"2012-07-07 09:10:10","context":"离开 [北京石景山营业厅] 派送中，递送员[温]，电话[]"},
             {"time":"2012-07-06 19:46:38","context":"到达 [北京石景山营业厅]"},
             {"time":"2012-07-06 15:22:32","context":"离开 [北京石景山营业厅] 派送中，递送员[温]，电话[]"},
             {"time":"2012-07-06 15:05:00","context":"到达 [北京石景山营业厅]"},
             {"time":"2012-07-06 13:37:52","context":"离开 [北京_同城中转站] 发往 [北京石景山营业厅]"},
             {"time":"2012-07-06 12:54:41","context":"到达 [北京_同城中转站]"},
             {"time":"2012-07-06 11:11:03","context":"离开 [北京运转中心驻站班组] 发往 [北京_同城中转站]"},
             {"time":"2012-07-06 10:43:21","context":"到达 [北京运转中心驻站班组]"},
             {"time":"2012-07-05 21:18:53","context":"离开 [福建_厦门支公司] 发往 [北京运转中心_航空]"},
             {"time":"2012-07-05 20:07:27","context":"已取件，到达 [福建_厦门支公司]"}
            ]}';*/
        print_r($get_content);
        exit();
    }






}